package com.uiao.timetask;

import org.quartz.*;
import org.quartz.impl.JobDetailImpl;
import org.quartz.impl.StdSchedulerFactory;

import static org.quartz.DateBuilder.evenHourDate;
import static org.quartz.DateBuilder.futureDate;
import static org.quartz.JobBuilder.*;
import static org.quartz.SimpleScheduleBuilder.*;

import org.quartz.Trigger;
import org.quartz.TriggerBuilder;

/**
 * @author uiao
 * @Title: QuartzTest JobDetail和trigger可以多个 所以用withIdentity
 * @Description: 定时任务调度器
 * @date 2018/7/1610:43
 */
public class QuartzTest {

    public static void main(String[] args) {
        try {
            // 创建调度器
            Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
            scheduler.start();

            // 创建任务详情
            JobDetail job = JobBuilder.newJob(HelloJob.class)
                    .withIdentity("job1", "group1")
                    .usingJobData("jobSays","你好")
                    .usingJobData("myFloatValue",222f)
                    .build();

            /*
            * 创建Simple触发器
            * 可以制定具体的执行时间和结束时间，制定多长时间执行一次，重复多少次
            */
            // 每8秒一次，不停
            Trigger trigger = TriggerBuilder.newTrigger().withIdentity("trigger1", "group1")
                    .startNow()// 现在开始
                    .withSchedule(simpleSchedule().withIntervalInSeconds(8).repeatForever())
                    .build();

            // 五分钟之后触发，只执行一次
            Trigger trigger1 = TriggerBuilder.newTrigger()
                    .withIdentity("trigger2", "group1")
                    .startAt(futureDate(5, DateBuilder.IntervalUnit.MINUTE)) // use DateBuilder to create a date in the future
                    .forJob(job) // identify job with its JobKey
                    .build();

            // 下一个小时整点触发，没两个小时执行一次
            Trigger trigger2 = TriggerBuilder.newTrigger()
                    .withIdentity("trigger3") // because group is not specified, "trigger8" will be in the default group
                    .startAt(evenHourDate(null)) // get the next even-hour (minutes and seconds zero ("00:00"))
                    .withSchedule(simpleSchedule()
                            .withIntervalInHours(2)
                            .repeatForever())
                    .build();


             /*
            * 创建CronTrigger触发器
            * 基于日历，很强大
            */
            CronTrigger cronTrigger = null;

            scheduler.scheduleJob(job, trigger);

            Thread.sleep(50000);
            scheduler.shutdown();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
